/*
 * @Author: lihaogn
 * @Date: 2021-12-18 11:19:30
 * @LastEditTime: 2021-12-23 14:43:28
 * @LastEditor: lihaogn
 * @Description: 角色 - controller
 * @FilePath: \lix-admin-server\app\controller\role.js
 */
const Controller = require("egg").Controller;
const { SuccessResponse, ErrorResponse } = require("../dto/responseDto");

class RoleController extends Controller {
  /**
   * @author: lihaogn
   * @Date: 2021-12-19 21:45:28
   * @description: 查询角色
   * @param {*}
   * @return {*}
   */
  async index() {
    const { ctx } = this;
    try {
      const res = await ctx.service.role.queryRoles();
      if (res === false) {
        ctx.body = new ErrorResponse(null, "获取角色数据失败");
      } else {
        ctx.body = new SuccessResponse(res, "");
      }
    } catch (error) {
      console.log("获取角色信息err:", error);
    }
  }

  /**
   * @author: lihaogn
   * @Date: 2021-12-19 21:53:59
   * @description: 新增角色
   * @param {*}
   * @return {*}
   */
  async create() {
    const { ctx } = this;
    try {
      const res = await ctx.service.role.createRole(ctx.request.body);
      if (res === false) {
        ctx.body = new ErrorResponse(null, "新增失败");
      } else {
        ctx.body = new SuccessResponse(res, "新增成功");
      }
    } catch (error) {
      console.log("获取角色信息err:", error);
    }
  }

  /**
   * @author: lihaogn
   * @Date: 2021-12-20 00:58:24
   * @description: 修改角色信息
   * @param {*}
   * @return {*}
   */
  async update() {
    const { ctx } = this;

    let res;
    let updateType = ctx.request.body.type;
    if (updateType === "UPDATE") {
      // 更新角色信息
      res = await ctx.service.role.updateRole(ctx.params.id, ctx.request.body);
    } else if (updateType === "UPDATE_PERMISSION") {
      // 更新角色权限
      res = await ctx.service.role.updateRolePermission(
        ctx.params.id,
        ctx.request.body
      );
    }

    if (res === false) {
      ctx.body = new ErrorResponse(null, "修改失败");
    } else {
      ctx.body = new SuccessResponse(null, "修改成功");
    }
  }

  /**
   * @author: lihaogn
   * @Date: 2021-12-20 20:51:29
   * @description: 删除角色
   * @param {*}
   * @return {*}
   */
  async destroy() {
    const { ctx } = this;

    const res = ctx.service.role.deleteRole(ctx.params.id);
    if (res === false) {
      ctx.body = new ErrorResponse(null, "删除失败");
    } else {
      ctx.body = new SuccessResponse(null, "删除成功");
    }
  }
}

module.exports = RoleController;
